import { messageId, EventType, type PostMessageEvent } from '@shared/index'

chrome.runtime.onMessage.addListener((event, sender) => {
  if (event?.messageId === messageId) {
    switch (event.type) {
      case EventType.CONNECT:
        sendMessage(sender.tab?.id!, { type: EventType.CONNECT })
        break
    }
  }
  return false
})

export function sendMessage(tabId: number, event: PostMessageEvent) {
  chrome.tabs.sendMessage(tabId, { ...event, messageId })
}

export function sendMessageToActiveTab(event: PostMessageEvent) {
  chrome.tabs.query({ active: true, lastFocusedWindow: true }).then(([tab]) => {
    tab?.id && sendMessage(tab.id, event)
  })
}
